package org.sbbs.app.license.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.sbbs.app.license.dao.ProductInfoDao;
import org.sbbs.app.license.model.Product;
import org.sbbs.app.license.model.ProductInfo;
import org.sbbs.app.license.service.ProductInfoManager;
import org.sbbs.base.service.impl.BaseManagerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.googlecode.genericdao.search.Search;

@Service( "productInfoManager" )
public class ProductInfoManagerImpl
    extends BaseManagerImpl<ProductInfo, String>
    implements ProductInfoManager {
    ProductInfoDao productInfoDao;

    @Autowired
    public ProductInfoManagerImpl( ProductInfoDao productInfoDao ) {
        super( productInfoDao );
        this.productInfoDao = productInfoDao;
    }

    @Override
    public void enableProductInfo( String[] ids ) {
        this.updateDisabledFlag( ids, false );

    }

    @Override
    public void disableProductInfo( String[] ids ) {
        this.updateDisabledFlag( ids, true );

    }

    private void updateDisabledFlag( String[] ids, Boolean newflag ) {
        this.productInfoDao.updateDisabledFlag( ids, newflag );
    }

    @Override
    public List<ProductInfo> findAllEnabledProductInfoes() {
        Search s = new Search();
        s.addFilterEqual( "disabled", false );
        return this.search( s );
    }

    @Override
    public List<Product> fitProducts( List<Product> pl ) {
        List<Product> nl = new ArrayList<Product>();
        for ( Iterator iterator = pl.iterator(); iterator.hasNext(); ) {
            Product product = (Product) iterator.next();
            if ( !product.getProductId().trim().equalsIgnoreCase( "" ) ) {
                ProductInfo pi = this.productInfoDao.find( product.getProductId().trim() );

                if ( pi != null ) {
                    product.setProductName( pi.getProductName() );
                    nl.add( product );
                }
            }
        }

        return nl;
    }
}
